package com.bt7274.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.DeleteRequest;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.bt7274.service.EsService;
import com.bt7274.pojo.EsPost;
import com.bt7274.pojo.Post;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class EsServiceImpl implements EsService {

    private final ElasticsearchClient client;

    public EsServiceImpl(ElasticsearchClient client) {
        this.client = client;
    }

    public List<String> searchPostIdsByKeywordAndAuthor(String keyword, String author) throws IOException {
        List<String> postIds = new ArrayList<>();

        BoolQuery.Builder boolQuery = new BoolQuery.Builder();

        if (keyword != null && !keyword.isBlank()) {
            boolQuery.must(Query.of(q -> q.match(m -> m
                    .field("title")
                    .query(keyword)
            )));
        }
        if (author != null && !author.isBlank()) {
            boolQuery.must(Query.of(q -> q.queryString(qs -> qs
                    .fields("userName")
                    .query("*" + author + "*")
            )));
        }

        SearchRequest request = SearchRequest.of(s -> s
                .index("post_index")
                .query(q -> q.bool(boolQuery.build()))
                .source(src -> src.filter(f -> f.includes("id")))
                .size(1000)
        );

        SearchResponse<EsPost> response = client.search(request, EsPost.class);

        for (Hit<EsPost> hit : response.hits().hits()) {
            if (hit.source() != null) {
                postIds.add(String.valueOf(hit.source().getId()));
            }
        }

        return postIds;
    }

    public void createOrUpdateEsPost(Post post, String userName) throws IOException {
        EsPost esPost = new EsPost(post.getId(), post.getTitle(), userName);

        IndexRequest<EsPost> request = IndexRequest.of(i -> i
                .index("post_index")
                .id(String.valueOf(post.getId()))
                .document(esPost)
        );

        client.index(request);
    }

    public void deleteEsPost(String postId) throws IOException {
        DeleteRequest request = DeleteRequest.of(d -> d
                .index("post_index")
                .id(postId)
        );

        client.delete(request);
    }
}
